package com.shangjinrong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shangjinrong.domain.BorrowInfo;
import com.shangjinrong.domain.Borrower;
import com.shangjinrong.domain.IntegralGrade;
import com.shangjinrong.domain.UserInfo;
import com.shangjinrong.domain.vo.BorrowInfoApprovalVO;
import com.shangjinrong.domain.vo.BorrowInfoDetailVO;
import com.shangjinrong.enums.BorrowInfoStatusEnum;
import com.shangjinrong.enums.BorrowerStatusEnum;
import com.shangjinrong.excption.Assert;
import com.shangjinrong.mapper.BorrowInfoMapper;
import com.shangjinrong.mapper.BorrowerMapper;
import com.shangjinrong.mapper.IntegralGradeMapper;
import com.shangjinrong.mapper.UserInfoMapper;
import com.shangjinrong.result.ResponseEnum;
import com.shangjinrong.service.BorrowInfoService;
import com.shangjinrong.service.DictService;
import com.shangjinrong.service.LendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Autowired
    private LendService lendService;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private IntegralGradeMapper integralGradeMapper;

    @Autowired
    private DictService dictService;

    @Resource
    private BorrowerMapper borrowerMapper;

    @Override
    public void approval(BorrowInfoApprovalVO borrowerInfoApprovalVo) {

        //修改借款审核状态
        Long borrowInfoId = borrowerInfoApprovalVo.getId();

        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);

        borrowInfo.setStatus(borrowerInfoApprovalVo.getStatus().byteValue());

        baseMapper.updateById(borrowInfo);

        //如果审核状态为已通过，则自动生成标的信息
        if (borrowerInfoApprovalVo.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()) {
            //创建新标的
            lendService.createLend(borrowerInfoApprovalVo, borrowInfo);
        }
    }

    @Override
    public BigDecimal getBorrowAmount(Long userId) {
        Integer integral = userInfoMapper.selectById(userId).getIntegral();

        LambdaQueryWrapper<IntegralGrade> wrapper = new LambdaQueryWrapper();
        wrapper.le(IntegralGrade::getIntegralStart, integral)
                .ge(IntegralGrade::getIntegralEnd, integral);
        IntegralGrade integralGrade = integralGradeMapper.selectOne(wrapper);

        if (null == integralGrade) return new BigDecimal("0");
        return integralGrade.getBorrowAmount();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //用户绑定状态
//        Assert.isTrue(
//                userInfo.getBindStatus().intValue() == UserBindEnum.OK_BIND.getStatus()
//                , ResponseEnum.USER_NO_BIND_ERROR);

        //用户信息是否审批通过
//        Assert.isTrue(
//                userInfo.getBorrowAuthStatus() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()
//                ,ResponseEnum.USER_NO_AMOUNT_ERROR);

        //借款额度是否足够
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        Assert.isTrue(
                borrowInfo.getAmount().doubleValue() <= borrowAmount.doubleValue()
                , ResponseEnum.USER_AMOUNT_LESS_ERROR);

        borrowInfo.setUserId(userId);
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus().byteValue());
        baseMapper.insert(borrowInfo);
    }

    @Override
    public Integer getStatusByUserId(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //用户信息是否审批通过
        Assert.isTrue(
                userInfo.getBorrowAuthStatus() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()
                , ResponseEnum.USER_NO_AMOUNT_ERROR);

        LambdaQueryWrapper<BorrowInfo> wrapper = new LambdaQueryWrapper();
        wrapper.select(BorrowInfo::getStatus).eq(BorrowInfo::getUserId, userId);
        List<Object> list = baseMapper.selectObjs(wrapper);
        if (list.size() == 0) {
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        return (Integer) list.get(0);
    }

    @Override
    public void paging(Page page) {
        baseMapper.selectPage(page, new QueryWrapper<>());
        List<BorrowInfo> list = page.getRecords();
        List<BorrowInfoDetailVO> borrowInfoDetailVOList = new ArrayList<>();


        list.forEach(borrowInfo -> {
            BorrowInfoDetailVO borrowInfoDetailVO = new BorrowInfoDetailVO();

            UserInfo userInfo = userInfoMapper.selectById(borrowInfo.getUserId());
            borrowInfoDetailVO.setName(userInfo.getName());
            borrowInfoDetailVO.setMobile(userInfo.getMobile());

            borrowInfoDetailVO.setId(borrowInfo.getId());
            borrowInfoDetailVO.setAmount(borrowInfo.getAmount());
            borrowInfoDetailVO.setPeriod(borrowInfo.getPeriod());
            borrowInfoDetailVO.setBorrowYearRate(borrowInfo.getBorrowYearRate());
            borrowInfoDetailVO.setCreateTime(borrowInfo.getCreateTime());

            borrowInfoDetailVO.setReturnMethod(
                    dictService.getNameByParentDictCodeAndValue("returnMethod"
                            , borrowInfo.getReturnMethod().intValue()));
            borrowInfoDetailVO.setMoneyUse(
                    dictService.getNameByParentDictCodeAndValue("moneyUse"
                            , borrowInfo.getMoneyUse().intValue()));
            borrowInfoDetailVO.setStatus(
                    BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus()));
            borrowInfoDetailVOList.add(borrowInfoDetailVO);

        });

        page.setRecords(borrowInfoDetailVOList);
    }

    @Override
    public BorrowInfoDetailVO getBorrowInfoDetail(Long id) {
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        BorrowInfoDetailVO borrowInfoDetailVO = new BorrowInfoDetailVO();

        borrowInfoDetailVO.setId(borrowInfo.getId());
        borrowInfoDetailVO.setAmount(borrowInfo.getAmount());
        borrowInfoDetailVO.setPeriod(borrowInfo.getPeriod());
        borrowInfoDetailVO.setBorrowYearRate(borrowInfo.getBorrowYearRate());
        borrowInfoDetailVO.setCreateTime(borrowInfo.getCreateTime());

        borrowInfoDetailVO.setReturnMethod(
                dictService.getNameByParentDictCodeAndValue("returnMethod"
                        , borrowInfo.getReturnMethod().intValue()));
        borrowInfoDetailVO.setMoneyUse(
                dictService.getNameByParentDictCodeAndValue("moneyUse"
                        , borrowInfo.getMoneyUse().intValue()));
        borrowInfoDetailVO.setStatus(
                BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus()));

        LambdaQueryWrapper<Borrower> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Borrower::getUserId, borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(wrapper);

        borrowInfoDetailVO.setName(borrower.getName());
        borrowInfoDetailVO.setMobile(borrower.getMobile());
        borrowInfoDetailVO.setIdCard(borrower.getIdCard());
        borrowInfoDetailVO.setSex(borrower.getSex() == 1 ? "男" : "女");
        borrowInfoDetailVO.setAge(borrower.getAge());
        borrowInfoDetailVO.setIsMarry(borrower.getIsMarry() ? "是" : "否");
        String education = dictService.getNameByParentDictCodeAndValue(
                "education", borrower.getEducation().intValue());
        borrowInfoDetailVO.setEducation(education);
        String industry = dictService.getNameByParentDictCodeAndValue(
                "industry", borrower.getIndustry().intValue());
        borrowInfoDetailVO.setIndustry(industry);
        String income = dictService.getNameByParentDictCodeAndValue(
                "income", borrower.getIncome().intValue());
        borrowInfoDetailVO.setIncome(income);
        String returnSource = dictService.getNameByParentDictCodeAndValue(
                "returnSource", borrower.getReturnSource().intValue());
        borrowInfoDetailVO.setReturnSource(returnSource);
        borrowInfoDetailVO.setBorrowerStatus(
                BorrowerStatusEnum.getMsgByStatus(borrower.getStatus().intValue()));
        borrowInfoDetailVO.setBorrowerCreateTime(borrower.getCreateTime());

        return borrowInfoDetailVO;
    }
}
